package udp

import (
	"fmt"
	"net"
	"os"
)

var limitChan = make(chan bool, 1000)

func StartUDP(port int) {
	ipAddr := &net.UDPAddr{
		IP:   net.IPv4(255, 255, 255, 255),
		Port: port,
		Zone: "",
	}

	udpConn, err := net.ListenUDP("udp", ipAddr)
	if err != nil {
		fmt.Println("start udp provider error")
	}

	msg := "hello,world"

	ret, err2 := udpConn.Write([]byte(msg))

	if err2 != nil {
		fmt.Println("something wrong")
	}

	fmt.Println(ret)
}

func StartUDPV2(port int) {
	udpAddr, err := net.ResolveUDPAddr("udp", "127.0.0.1:9096")
	conn, err := net.ListenUDP("udp", udpAddr)
	defer conn.Close()
	if err != nil {
		fmt.Println("read from connected failed, err " + err.Error())
		os.Exit(1)
	}

	for {
		limitChan <- true
		go udpProcess(conn)
	}
}

//UDP goroutine 实现并发读取UDP数据
func udpProcess(conn *net.UDPConn) {

	// 最大读取数据大小
	data := make([]byte, 1024)
	n, _, err := conn.ReadFromUDP(data)
	if err != nil {
		fmt.Println("failed read udp msg, error: " + err.Error())
	}
	str := string(data[:n])
	fmt.Println("receive from client, data:" + str)
	<-limitChan
}
